/*************************************************************************
	> File Name: log.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/02 16:43
 ************************************************************************/

#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <cstdarg>
#include <ctime>

const int DEBUG =   0;
const int NORMAL =  1;
const int WARNING = 2;
const int ERROR =   3;
const int FATAL =   4;

const int STD_SIZE = 64;
const int LOG_SIZE = 1024;
const int TIME_SIZE = 32;

const std::string logFile = "./file.log";

const std::string gLevelMap[] = {
    "DEBUG",
    "NORMAL",
    "WARNING",
    "ERROR",
    "FATAL"
};

void logMessage(int level, char *format, ...)
{
#ifndef DEBUG_SHOW
    if (level == DEBUG) {
        return ;
    }
#endif
    char stdBuffer[STD_SIZE];
    char logBuffer[LOG_SIZE];
    char timeBuffer[TIME_SIZE];
    const time_t t = time(nullptr);
    const struct tm *timeinfo = localtime(&t);
    strftime(timeBuffer, sizeof timeBuffer, "%Y-%m-%d %H:%M:%S", timeinfo);
    snprintf(stdBuffer, sizeof stdBuffer, "[%s][%s]", gLevelMap[level].c_str(), timeBuffer);
    va_list args;
    va_start(args, format);
    vsnprintf(logBuffer, sizeof logBuffer, format, args);
    va_end(args);
#ifdef LOG_FILE
    FILE *fp = fopen(logFile.c_str(), "a");
    fprintf(fp, "%s%s\n", stdBuffer, logBuffer);
    fclose(fp);
#else
    printf("%s%s\n", stdBuffer, logBuffer);
#endif
}
